<template>
  <div id="public-microstation">
    <div class="row row-2">
      <div class="col">
        <div id="leaflet-public-microstation" class="leaflet"></div>
        <div
          :class="velocityShow === 1 ? 'velocity active' : 'velocity'"
          @click="showVelocity()"
        ></div>
        <div class="flush" @click="flushVelocity()"></div>
      </div>
    </div>
    <div class="row row-3">
      <div class="col col-1">
        <p
          :class="
            showKeyWord.toLowerCase() === 'temperature' ? 'item active' : 'item'
          "
          @click="createMarkerByKey('temperature')"
        >
          温度
        </p>
      </div>
      <div class="col col-2">
        <p
          :class="
            showKeyWord.toLowerCase() === 'humidity' ? 'item active' : 'item'
          "
          @click="createMarkerByKey('humidity')"
        >
          湿度
        </p>
      </div>
      <div class="col col-3">
        <p
          :class="
            showKeyWord.toLowerCase() === 'windspeed' ? 'item active' : 'item'
          "
          @click="createMarkerByKey('windspeed')"
        >
          风速
        </p>
      </div>
      <div class="col col-4">
        <p
          :class="
            showKeyWord.toLowerCase() === 'pressure' ? 'item active' : 'item'
          "
          @click="createMarkerByKey('pressure')"
        >
          气压
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import L from "leaflet";
import "../../assets/leaflet/leaflet.ChineseTmsProviders.js";
import "../../assets/leaflet/leaflet-velocity.js";
import {
  getDistrictByCondition,
  findHourlyStatisticsListByCondition,
  getVelocityData
} from "../../axios/api";

export default {
  data() {
    return {
      map: null,
      mapOption: {
        zoom: 12
      },
      layers: [],
      paramsGroup: null,
      showKeyWord: "humidity",
      deviceDataList: {},
      colorScale: ["#ff0"],
      velocityShow: 0,
      velocityLayer: null,
      velocityData: [],
      districtDataList: [],
      districtId: null,
      districtData: {},
      layerGroup: null,
      defaultDistrictId: 8,
      defaultDistrictType: 3
    };
  },
  methods: {
    // 初始化
    init() {
      let districtId = this.$route.query.districtId;
      this.districtId = districtId ? districtId : this.defaultDistrictId;
      this.getDistrictData();
    },
    // 获取行政区域信息
    getDistrictData() {
      getDistrictByCondition(
        {
          districtId: this.districtId,
          type: this.defaultDistrictType
        },
        data => {
          this.districtData = data;
          this.initMap();
          this.loadRegion();
          this.findHourlyStatisticsListByCondition();
          this.getVelocityData();
        },
        () => {}
      );
    },
    // 获取网络数据
    findHourlyStatisticsListByCondition() {
      // 获取统计数据
      findHourlyStatisticsListByCondition(
        {
          districtId: this.districtId
        },
        data => {
          console.log(data);
          this.dataConversion(data);
        },
        () => {
          this.dataConversion([]);
        }
      );
    },
    getVelocityData() {
      // 获取风场数据
      getVelocityData(
        {
          districtId: this.districtId,
          type: this.defaultDistrictType
        },
        data => {
          this.velocityData = data;
        },
        () => {
          this.velocityData = [];
        }
      );
    },
    // 初始化地图
    initMap() {
      this.map = L.map("leaflet-public-microstation", {
        center: [this.districtData.lat, this.districtData.lng],
        zoom: this.mapOption.zoom
      });

      L.tileLayer(
        "http://t{s}.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={z}&TileRow={y}&TileCol={x}&style=default&format=tiles&tk=bebf738d00ce5ce52058e5d1619d4f5c",
        {
          maxZoom: 18,
          minZoom: 9,
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
          detectRetina: true
        }
      ).addTo(this.map);

      L.tileLayer(
        "https://t{s}.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=bebf738d00ce5ce52058e5d1619d4f5c",
        {
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"]
        }
      ).addTo(this.map);
    },
    // 初始化地图边界
    loadRegion() {
      let regionLayer = new L.geoJSON(JSON.parse(this.districtData.geojson), {
        style: function() {
          return {
            fillColor: "transparent",
            color: "#ff0"
          };
        }
      });
      this.layerGroup = new L.LayerGroup();
      this.layerGroup.addLayer(regionLayer);
      this.layerGroup.addTo(this.map);
    },
    // 数据格式转换
    dataConversion(data) {
      this.deviceDataList = {};
      data.forEach(item => {
        if (item.hourly) {
          console.log(item.hourly);
          this.deviceDataList[item.deviceId] = {
            device: item.device,
            hourly: item.hourly
          };
        }
      });
      this.createMarker(this.showKeyWord);
    },
    createMarker(keyword) {
      this.paramsGroup = new L.layerGroup();
      for (let key in this.deviceDataList) {
        if (this.deviceDataList.hasOwnProperty(key)) {
          let item = this.deviceDataList[key];
          let address = item.device.alias;
          let param;
          let className;
          if (keyword.toLowerCase() === "temperature") {
            param = item.hourly.temperature;
            className = "warn-color-1";
          } else if (keyword.toLowerCase() === "humidity") {
            param = item.hourly.humidity;
            className = "warn-color-1";
          } else if (keyword.toLowerCase() === "windspeed") {
            param = item.hourly.windSpeed;
            className = "warn-color-1";
          } else if (keyword.toLowerCase() === "pressure") {
            param = item.hourly.pressure;
            className = "warn-color-1";
          }

          let np1 = this.gps.bd_decrypt(item.device.lat, item.device.lng);
          let np2 = this.gps.gcj_decrypt(np1.lat, np1.lng);
          let point = [np2.lat, np2.lng];
          let params = {
            point: point,
            className: className,
            aqi: param,
            deviceId: item.device.deviceId,
            address: address
          };
          this.createMarkerCircle(params);
          this.createMarkerAddress(params);
          this.createMarkerAqi(params);
        }
      }
      this.paramsGroup.addTo(this.map);
    },
    createMarkerCircle(data) {
      let icon = L.divIcon({
        html: `<div class="${data.className}"></div>`,
        className: "circle-icon",
        iconSize: [10, 10],
        iconAnchor: [5, 10]
      });

      let marker = L.marker(data.point, {
        icon: icon
      });
      this.paramsGroup.addLayer(marker);
    },
    createMarkerAddress(data) {
      let width = data.address.length * 15;
      let icon = L.divIcon({
        html: `<p class="${data.className} ellipsis">${data.address}</p>`,
        className: "address-icon",
        iconSize: [width, 20],
        iconAnchor: [width / 2, -6]
      });

      let marker = L.marker(data.point, {
        icon: icon
      }).addTo(this.map);

      this.paramsGroup.addLayer(marker);
    },
    createMarkerAqi(data) {
      let icon = L.divIcon({
        html: `<div class="aqi ${data.className}">
               <p class="ellipsis">${data.aqi}</p>
               <div class="hornlike"></div>
            </div>`,
        className: "aqi-icon",
        iconSize: [50, 22],
        iconAnchor: [25, 45],
        popupAnchor: [0, -18]
      });

      let marker = new L.marker(data.point, {
        icon: icon,
        maxWidth: 280
      });

      this.paramsGroup.addLayer(marker);
      marker.addEventListener("click", () => {
        this.selectedDeviceId = data.deviceId;
        this.createPopup(data);
      });
    },
    createPopup(data) {
      let item = this.deviceDataList[data.deviceId];
      let aqiParams = {
        hourly: item.hourly,
        device: item.device
      };
      aqiParams.id = data.deviceId + "-" + new Date().getTime();
      let content = this.getLeafletPopupHtmlTemplate(aqiParams);
      L.popup({
        maxWidth: 200,
        offset: L.point(1, -3)
      })
        .setLatLng(data.point)
        .setContent(content)
        .openOn(this.map);
    },
    getLeafletPopupHtmlTemplate(aqiParams) {
      return `<div class="container">
            <div class="row row-1">
              <div class="col col-1">
                <div class="row row-1">
                  <p class="ellipsis">${aqiParams.device.alias}</p>
                </div>
                <div class="row row-2">
                  <p class="ellipsis">${aqiParams.hourly.statsTime}</p>
                </div>
              </div>
            </div>
            <div class="row row-2">
              <p class="ellipsis">${aqiParams.device.address}</p>
            </div>
            <div class="row row-4"></div>
            <div class="row row-5">
              <div class="col col-1">
                <p class="ellipsis">${aqiParams.hourly.temperature}℃</p>
              </div>
              <div class="col col-2">
                <p class="ellipsis">${aqiParams.hourly.humidity}%</p>
              </div>
              <div class="col col-3">
                <p class="ellipsis">${aqiParams.hourly.pressure}kPa</p>
              </div>
              <div class="col col-4">
                <p class="ellipsis">${this.utils.validateWindDirection(
                  aqiParams.hourly.windDirection,
                  aqiParams.hourly.windSpeed
                )}</p>
              </div>
              <div class="col col-5">
                <p class="ellipsis">${aqiParams.hourly.windSpeed}m/s</p>
              </div>
            </div>
          </div>`;
    },
    showVelocity() {
      if (this.velocityShow === 0 && this.velocityData) {
        this.velocityLayer = L.velocityLayer({
          displayValues: true,
          displayOptions: {
            velocityType: "风",
            position: "bottomleft",
            emptyString: "未知",
            angleConvention: "bearingCW",
            displayPosition: "bottomleft",
            displayEmptyString: "未知",
            speedUnit: "m/s"
          },
          data: this.velocityData, // see demo/*.json, or wind-js-server for example data service

          // OPTIONAL
          minVelocity: 0, // 粒子的最小速度  0
          maxVelocity: 10, // 粒子的最大速度  10
          velocityScale: 0.015, // 风速的尺度 || 粒子尾巴长度  0.005
          colorScale: this.colorScale, // 粒子颜色
          lineWidth: 2, // 线条宽度  1
          particleMultiplier: 1 / 1300, // 粒子密度 1 / 2600
          frameRate: 10, // 每秒所需帧数  10
          onAdd: null, // callback function
          onRemove: null // callback function
        });
        this.velocityLayer.addTo(this.map);
      } else {
        this.map.removeLayer(this.velocityLayer);
      }
      this.velocityShow = 1 - this.velocityShow;
    },
    createMarkerByKey(key) {
      this.clearMarker();
      this.showKeyWord = key.toLowerCase();
      this.createMarker(key);
    },
    clearMarker() {
      this.layers = [];
      this.map.closePopup();
      if (this.paramsGroup !== null) {
        this.map.removeLayer(this.paramsGroup);
      }
    },
    flushVelocity() {
      this.clearMarker();
      if (this.velocityShow === 1 && this.velocityLayer) {
        this.map.removeLayer(this.velocityLayer);
        this.velocityShow = 0;
      }
      this.getData();
    },
    // 切换区域
    districtUpdate() {
      this.districtData = this.getDistrictData();
      // // 重新绘制地图边界
      this.updateMap();
      this.flushVelocity();
    },
    // 重绘地图
    updateMap() {
      // 清除地图边界
      this.clearRegion();
      // 绘制地图边界
      this.initRegion();
      // 移动地图中心
      this.updateMapCenter();
    },
    // 清除地图边界
    clearRegion() {
      if (this.layerGroup !== null) {
        this.map.removeLayer(this.layerGroup);
      }
    },
    // 移动地图中心点
    updateMapCenter() {
      this.map.panTo([this.districtData.lat, this.districtData.lng]);
    }
  },
  mounted() {
    // 获取行政区域列表
    this.init();
  }
};
</script>

<style lang="stylus" scoped>
@import "../../assets/css/common.styl"
#public-microstation
    position relative
    width 100%
    height 100%

    > .row-2
        position absolute
        top 0
        bottom 33px
        width 100%

        > .col
            width 100%
            height 100%
            background-color #666

            > .leaflet
                position relative
                width 100%
                height 100%

                >>> .leaflet-marker-icon.address-icon

                    line-height 18px
                    text-align center

                    p
                        font-size 12px
                        border-radius 5px
                        background-color rgba(255, 255, 255, .8)

                >>> .leaflet-marker-icon.circle-icon
                    div
                        width 10px
                        height 10px
                        border-radius 50%

                >>> .leaflet-marker-icon.aqi-icon

                    > .aqi
                        position relative
                        border-radius 5px
                        text-align center
                        line-height 20px
                        font-size 14px
                        color #fff

                        > .hornlike
                            position absolute
                            left 18px
                            bottom -10px
                            margin -5px 0 0 5px
                            border-left 1px solid transparent
                            border-right 8px solid transparent

                >>> .leaflet-popup-content-wrapper
                    color #000

                    > .leaflet-popup-content
                        position relative

                        > .container
                            position relative
                            width 200px
                            margin 0 auto

                            .row
                                position relative

                                > .col
                                    float left
                                    position relative

                            .row::after
                                content ''
                                display block
                                clear both

                            > .row-1
                                > .col-1
                                    width 150px

                                    > .row-1
                                        font-size 14px

                                    > .row-2
                                        font-size 12px
                                        color #6E6E6E

                                > .col-2
                                    width 50px

                                    > .row-1
                                        border-radius 3px
                                        text-align center
                                        line-height 16px
                                        font-size 14px
                                        color #fff

                            > .row-2
                                font-size 12px
                                color #6E6E6E

                            > .row-3
                                padding 10px 0 5px 0

                                > .col:nth-of-type(3n + 1)
                                    margin-left 0

                                > .col
                                    margin-left 7px

                                    > .row-1
                                        width 62px
                                        height 20px
                                        text-align center
                                        line-height 18px
                                        font-size 14px
                                        color #fff

                                        > p
                                            border-radius 8px

                                    > .row-2
                                        width 62px
                                        height 20px
                                        text-align center
                                        line-height 18px
                                        font-size 14px
                                        color #666

                            > .row-4
                                margin 10px -21px
                                height 1px
                                border none
                                background-color #6E6E6E

                            > .row-5
                                line-height 20px
                                padding 5px 0 10px 0

                                > .col:nth-of-type(2n + 1)
                                    margin-left 0

                                > .col
                                    margin-left 7px
                                    width 96px
                                    font-size 14px
                                    color #6E6E6E

                                    > p
                                        padding-left 17px

                                    > p::before
                                        content ''
                                        position absolute
                                        top 0
                                        left 0
                                        width 15px
                                        height 20px

                                > .col:nth-of-type(n + 3)
                                    margin-top 5px

                                > .col:nth-of-type(1)
                                    > p::before
                                        background url("../../assets/images/microStation/20190715173751.png") no-repeat 2px 5px
                                        background-size 121px 35px

                                > .col:nth-of-type(2)
                                    > p::before
                                        background url("../../assets/images/microStation/20190715173751.png") no-repeat -52px 5px
                                        background-size 121px 35px

                                > .col:nth-of-type(3)
                                    > p::before
                                        background url("../../assets/images/microStation/20190715173751.png") no-repeat -105px 4px
                                        background-size 121px 35px

                                > .col:nth-of-type(4)
                                    > p::before
                                        background url("../../assets/images/microStation/20190715173751.png") no-repeat 2px -19px
                                        background-size 121px 35px

                                > .col:nth-of-type(5)
                                    > p::before
                                        background url("../../assets/images/microStation/20190715173751.png") no-repeat -51px -17px
                                        background-size 121px 35px

                            > .row-6
                                height 120px

                                > .echarts
                                    height 120px


                >>> .leaflet-control-container
                    > .leaflet-bottom.leaflet-left
                        > .leaflet-control-velocity.leaflet-control
                            padding 5px 8px
                            background-color #fff
                            border-radius 5px

            > .velocity
                position absolute
                bottom 10px
                right 10px
                width 35px
                height 35px
                background-color rgba(255, 255, 255, 0.9)
                border 1px solid #666
                border-radius 5px
                z-index 999

            > .velocity::after
                content ''
                position absolute
                top 0
                left 0
                width 35px
                height 35px
                background url("../../assets/images/feng.png") no-repeat 5px 5px
                background-size 25px 25px

            > .velocity.active::after
                content ''
                position absolute
                top 0
                left 0
                width 35px
                height 35px
                background url("../../assets/images/feng-active.png") no-repeat 5px 5px
                background-size 25px 25px

            > .flush
                position absolute
                bottom 60px
                right 10px
                width 35px
                height 35px
                background-color rgba(255, 255, 255, 0.9)
                border 1px solid #666
                border-radius 5px
                z-index 999

            > .flush::after
                content ''
                position absolute
                top 0
                left 0
                width 35px
                height 35px
                background url("../../assets/images/20191129091455.png") no-repeat 5px 7px
                background-size 25px 22px

    > .row-3
        position absolute
        bottom 0
        left 0
        width 100%
        height 33px
        background-color #FFF

        > .col
            position relative
            width calc(25% - 1px)
            height 32px

            p
                line-height 32px
                text-align center
                font-size 14px
                color #333

        > .col-1, > .col-2, > .col-3
            border-bottom 1px solid #EEE
            border-right 1px solid #EEE

        > .col-4
            border-bottom 1px solid #EEE

        > .col
            > p.active
                background-color #00a0e9
                color #FFF

.el-select-dropdown
    > .el-scrollbar
        .el-select-dropdown__item
            text-align center
</style>
